<template>
  <div class="repayment-plan-container">
    <el-card class="repayment-plan-card">
      <template #header>
        <div class="card-header">
          <h2>{{ t('repaymentPlan.title') }}</h2>
          <div class="header-actions">
            <el-button @click="goBack">{{ t('repaymentPlan.back') }}</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else>
        <!-- 贷款信息 -->
        <div class="loan-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item :label="t('repaymentPlan.loanNo')">
              {{ loanInfo?.loanNo || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('repaymentPlan.status')">
              <el-tag :type="getLoanStatusType(loanInfo?.status)">
                {{ loanInfo?.statusText || '-' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :label="t('repaymentPlan.amount')">
              ¥ {{ loanInfo ? formatMoney(loanInfo.amount) : '-' }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('repaymentPlan.period')">
              {{ loanInfo?.period || '-' }} {{ t('repaymentPlan.months') }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('repaymentPlan.interestRate')">
              {{ loanInfo?.interestRate || '-' }}%
            </el-descriptions-item>
            <el-descriptions-item :label="t('repaymentPlan.loanTime')">
              {{ loanInfo?.loanTime ? formatDate(loanInfo.loanTime) : '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 还款计划 -->
        <div class="repayment-plan-list">
          <h3>{{ t('repaymentPlan.repaymentPlanList') }}</h3>
          
          <div class="repayment-summary">
            <div class="summary-item">
              <div class="label">{{ t('repaymentPlan.totalPeriods') }}</div>
              <div class="value">{{ repaymentStore.repaymentPlans.length }}</div>
            </div>
            <div class="summary-item">
              <div class="label">{{ t('repaymentPlan.paidPeriods') }}</div>
              <div class="value">{{ paidCount }}</div>
            </div>
            <div class="summary-item">
              <div class="label">{{ t('repaymentPlan.unpaidPeriods') }}</div>
              <div class="value">{{ unpaidCount }}</div>
            </div>
            <div class="summary-item">
              <div class="label">{{ t('repaymentPlan.overduePeriods') }}</div>
              <div class="value">{{ overdueCount }}</div>
            </div>
          </div>
          
          <el-table
            :data="repaymentStore.repaymentPlans"
            style="width: 100%"
            :default-sort="{ prop: 'period', order: 'ascending' }"
          >
            <el-table-column prop="period" :label="t('repaymentPlan.periodNum')" width="80" sortable />
            <el-table-column prop="repayDate" :label="t('repaymentPlan.repayDate')" width="120" sortable />
            <el-table-column prop="amount" :label="t('repaymentPlan.amount')" width="120">
              <template #default="scope">
                ¥ {{ formatMoney(scope.row.amount) }}
              </template>
            </el-table-column>
            <el-table-column prop="principal" :label="t('repaymentPlan.principal')" width="120">
              <template #default="scope">
                ¥ {{ formatMoney(scope.row.principal) }}
              </template>
            </el-table-column>
            <el-table-column prop="interest" :label="t('repaymentPlan.interest')" width="120">
              <template #default="scope">
                ¥ {{ formatMoney(scope.row.interest) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" :label="t('repaymentPlan.status')" width="100">
              <template #default="scope">
                <el-tag :type="getRepaymentStatusType(scope.row.status)">
                  {{ scope.row.statusText }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="actualRepayTime" :label="t('repaymentPlan.actualRepayTime')" width="180">
              <template #default="scope">
                {{ scope.row.actualRepayTime ? formatDate(scope.row.actualRepayTime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('repaymentPlan.operations')" fixed="right" width="120">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === 0"
                  type="primary"
                  size="small"
                  @click="showRepayDialog(scope.row)"
                >
                  {{ t('repaymentPlan.repay') }}
                </el-button>
                <el-button
                  v-if="scope.row.status === 2"
                  type="danger"
                  size="small"
                  @click="showRepayDialog(scope.row)"
                >
                  {{ t('repaymentPlan.repayOverdue') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
    
    <!-- 还款对话框 -->
    <el-dialog
      v-model="repayDialogVisible"
      :title="t('repaymentPlan.repayDialog')"
      width="500px"
    >
      <div v-if="selectedPlan" class="repay-dialog-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item :label="t('repaymentPlan.periodNum')">
            {{ selectedPlan.period }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('repaymentPlan.repayDate')">
            {{ selectedPlan.repayDate }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('repaymentPlan.amount')">
            ¥ {{ formatMoney(selectedPlan.amount) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('repaymentPlan.status')">
            <el-tag :type="getRepaymentStatusType(selectedPlan.status)">
              {{ selectedPlan.statusText }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-form
          ref="repayFormRef"
          :model="repayForm"
          :rules="repayRules"
          label-width="120px"
          class="repay-form"
        >
          <el-form-item :label="t('repaymentPlan.repayType')" prop="repayType">
            <el-radio-group v-model="repayForm.repayType">
              <el-radio :label="0">{{ t('repaymentPlan.bankCard') }}</el-radio>
              <el-radio :label="1">{{ t('repaymentPlan.alipay') }}</el-radio>
              <el-radio :label="2">{{ t('repaymentPlan.wechat') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item 
            v-if="repayForm.repayType === 0" 
            :label="t('repaymentPlan.bankCard')" 
            prop="bankCardId"
          >
            <el-select 
              v-model="repayForm.bankCardId" 
              style="width: 100%;"
              :loading="bankCardsLoading"
            >
              <el-option 
                v-for="card in bankCards" 
                :key="card.id" 
                :label="`${card.bankName} (${formatCardNo(card.cardNo)})`" 
                :value="card.id" 
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="repayDialogVisible = false">
            {{ t('repaymentPlan.cancel') }}
          </el-button>
          <el-button 
            type="primary" 
            :loading="repayLoading"
            @click="handleRepay"
          >
            {{ t('repaymentPlan.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 还款成功对话框 -->
    <el-dialog
      v-model="repaySuccessDialogVisible"
      :title="t('repaymentPlan.repaySuccess')"
      width="500px"
    >
      <div class="repay-success-content">
        <el-result
          icon="success"
          :title="t('repaymentPlan.repaySuccess')"
          :sub-title="t('repaymentPlan.repaySuccessMessage')"
        >
          <template #extra>
            <el-button type="primary" @click="repaySuccessDialogVisible = false">
              {{ t('repaymentPlan.close') }}
            </el-button>
          </template>
        </el-result>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useLoanStore, useRepaymentStore, useBankCardStore, useUserStore } from 'store';
import { ElMessage } from 'element-plus';

// 国际化
const { t } = useI18n();

// 路由
const router = useRouter();
const route = useRoute();

// 状态
const loanStore = useLoanStore();
const repaymentStore = useRepaymentStore();
const bankCardStore = useBankCardStore();
const userStore = useUserStore();

// 贷款ID
const loanId = computed(() => parseInt(route.params.id));

// 贷款信息
const loanInfo = ref(null);

// 加载状态
const loading = ref(false);
const bankCardsLoading = ref(false);
const repayLoading = ref(false);

// 银行卡列表
const bankCards = computed(() => bankCardStore.bankCards);

// 还款计划统计
const paidCount = computed(() => {
  return repaymentStore.repaymentPlans.filter(plan => plan.status === 1).length;
});
const unpaidCount = computed(() => {
  return repaymentStore.repaymentPlans.filter(plan => plan.status === 0).length;
});
const overdueCount = computed(() => {
  return repaymentStore.repaymentPlans.filter(plan => plan.status === 2).length;
});

// 还款对话框
const repayDialogVisible = ref(false);
const selectedPlan = ref(null);
const repayFormRef = ref(null);
const repayForm = ref({
  repayType: 0,
  bankCardId: null
});

// 还款成功对话框
const repaySuccessDialogVisible = ref(false);

// 表单验证规则
const repayRules = {
  repayType: [
    { required: true, message: t('repaymentPlan.repayTypeRequired'), trigger: 'change' }
  ],
  bankCardId: [
    { 
      required: true, 
      message: t('repaymentPlan.bankCardRequired'), 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (repayForm.value.repayType === 0 && !value) {
          callback(new Error(t('repaymentPlan.bankCardRequired')));
        } else {
          callback();
        }
      }
    }
  ]
};

// 获取贷款状态类型
const getLoanStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 申请中
    1: 'warning', // 审核中
    2: 'danger',  // 已拒绝
    3: 'success', // 已通过
    4: 'success', // 已放款
    5: 'primary', // 还款中
    6: 'success', // 已结清
    7: 'danger'   // 已逾期
  };
  return statusMap[status] || 'info';
};

// 获取还款状态类型
const getRepaymentStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 未还
    1: 'success', // 已还
    2: 'danger'   // 逾期
  };
  return statusMap[status] || 'info';
};

// 格式化金额
const formatMoney = (amount) => {
  return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 格式化银行卡号
const formatCardNo = (cardNo) => {
  if (!cardNo) return '';
  return cardNo.substring(0, 4) + ' **** **** ' + cardNo.substring(cardNo.length - 4);
};

// 返回
const goBack = () => {
  router.push('/loan');
};

// 显示还款对话框
const showRepayDialog = (plan) => {
  selectedPlan.value = plan;
  
  // 重置表单
  repayForm.value = {
    repayType: 0,
    bankCardId: bankCardStore.defaultCard?.id || (bankCards.value.length > 0 ? bankCards.value[0].id : null)
  };
  
  repayDialogVisible.value = true;
};

// 处理还款
const handleRepay = async () => {
  if (!repayFormRef.value) return;
  
  await repayFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    repayLoading.value = true;
    try {
      const result = await repaymentStore.repay({
        userId: userStore.userId,
        loanId: loanId.value,
        repaymentPlanId: selectedPlan.value.id,
        amount: selectedPlan.value.amount,
        repayType: repayForm.value.repayType,
        bankCardId: repayForm.value.repayType === 0 ? repayForm.value.bankCardId : null
      });
      
      if (result) {
        repayDialogVisible.value = false;
        repaySuccessDialogVisible.value = true;
      }
    } finally {
      repayLoading.value = false;
    }
  });
};

// 获取贷款详情和还款计划
onMounted(async () => {
  if (!loanId.value) {
    ElMessage.error(t('repaymentPlan.invalidLoanId'));
    router.push('/loan');
    return;
  }
  
  loading.value = true;
  bankCardsLoading.value = true;
  
  try {
    // 获取贷款详情
    const loan = await loanStore.getLoanDetail(loanId.value);
    if (loan) {
      loanInfo.value = loan;
    }
    
    // 获取还款计划
    await repaymentStore.getLoanRepaymentPlans(loanId.value);
    
    // 获取银行卡列表
    await bankCardStore.getBankCards();
  } finally {
    loading.value = false;
    bankCardsLoading.value = false;
  }
});
</script>

<style scoped lang="scss">
.repayment-plan-container {
  max-width: 1000px;
  margin: 0 auto;
}

.repayment-plan-card {
  margin-bottom: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h2 {
      margin: 0;
      font-size: 18px;
    }
  }
}

.loading-container {
  padding: 20px 0;
}

.loan-info {
  margin-bottom: 30px;
}

.repayment-plan-list {
  h3 {
    margin-top: 0;
    margin-bottom: 20px;
  }
}

.repayment-summary {
  display: flex;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  
  .summary-item {
    flex: 1;
    text-align: center;
    
    .label {
      font-size: 14px;
      color: #606266;
      margin-bottom: 5px;
    }
    
    .value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
    }
  }
}

.repay-dialog-content {
  .repay-form {
    margin-top: 20px;
  }
}
</style>